语句
JavaScript 应用程序是由许多语法正确的语句组成的。
if...else
当指定条件为真,if 语句会执行一段语句。如果条件为假,则执行另一段语句。
if (x > 5) {
/* do the right thing */
} else if (x > 50) {
/* do the right thing */
} else {
/* do the right thing */
}
for
for 语句用于创建一个循环,它包含了三个可选的表达式,这三个表达式被包围在圆括号之中,使用分号分隔,后跟一个用于在循环中执行的语句(通常是一个块语句)。
let text = "";
for (let i = 0; i < 10; i++) {
if (i === 3) {
continue;
} else if (i === 5) {
break;
}
text = text + i;
}
console.log(text); // Expected output: "0124"
for in
for...in 语句以任意顺序迭代一个对象的除 Symbol 以外的可枚举属性,包括继承的可枚举属性。
var obj = { a: 1, b: 2, c: 3 };
for (var prop in obj) {
console.log("obj." + prop + " = " + obj[prop]);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
for of
for...of 语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
const array1 = ["a", "b", "c"];
for (const element of array1) {
console.log(element);
}
// Expected output: "a"
// Expected output: "b"
// Expected output: "c"
while
while 语句可以在某个条件表达式为真的前提下,循环执行指定的一段代码,直到那个表达式不为真时结束循环。
let n = 0;
while (n < 3) {
n++;
}
console.log(n);
// Expected output: 3
do...while
do...while 语句创建一个执行指定语句的循环,直到 condition 值为 false。在执行 statement 后检测 condition,所以指定的 statement 至少执行一次。
var result = "";
var i = 0;
do {
i += 1;
result += i + " ";
} while (i < 5);
console.log(result); // Expected output: 1 2 3 4 5
label
标记语句可以和 break 或 continue 语句一起使用。标记就是在一条语句前面加个可以引用的标识符(identifier)。
let str = "";
loop1: for (let i = 0; i < 5; i++) {
if (i === 1) {
continue loop1;
}
str = str + i;
}
console.log(str); // Expected output: "0234"
throw
throw 语句用来抛出一个用户自定义的异常。当前函数的执行将被停止(throw 之后的语句将不会执行),并且控制将被传递到调用堆栈中的第一个 catch 块。如果调用者函数中没有 catch 块,程序将会终止。
function getRectArea(width, height) {
if (isNaN(width) || isNaN(height)) {
throw new Error("Parameter is not a number!");
console.log(123);
}
}
try {
getRectArea(3, "A");
} catch (e) {
console.error(e);
// Expected output: Error: Parameter is not a number!
}
try...catch
try...catch 语句标记要尝试的语句块,并指定一个出现异常时抛出的响应。
try {
nonExistentFunction();
} catch (error) {
console.error(error);
// Expected output: ReferenceError: nonExistentFunction is not defined
// (Note: the exact output may be browser-dependent)
}
debugger
debugger 语句调用任何可用的调试功能,例如设置断点。如果没有调试功能可用,则此语句不起作用。